// src/store/userStore.js
import { defineStore } from "pinia";

export const useUserStore = defineStore("user", {
  // state: 返回状态对象
  state: () => ({
    userInfo: null,
    token: localStorage.getItem("token") || "",
    isLoggedIn: false,
  }),

  // getters: 计算属性
  getters: {
    getName: (state) => state.userInfo?.name || "游客",
    hasToken: (state) => !!state.token,
  },

  // actions: 同步 + 异步方法
  actions: {
    setToken(token) {
      this.token = token;
      this.isLoggedIn = true;
      localStorage.setItem("token", token);
    },
    removeToken() {
      this.token = "";
      this.isLoggedIn = false;
      this.userInfo = null;
      localStorage.removeItem("token");
    },
    setUserInfo(info) {
      this.userInfo = info;
    },
    Gettoken(token) {
      localStorage.setItem("token", token);
      this.token = localStorage.getItem("token");
      return this.token;
    },
    async fetchUserInfo() {
      try {
        const res = await fetch("/api/auth/profile", {
          headers: {
            Authorization: `Bearer ${this.token}`,
          },
        });
        const data = await res.json();
        this.setUserInfo(data);
        return data;
      } catch (error) {
        this.removeToken();
        throw error;
      }
    },
  },
});
